<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "sms_validator".
 *
 * @property string $id
 * @property string $name
 * @property string $mobile
 * @property string $code
 * @property integer $times
 * @property integer $created_at
 */
class SmsValidator extends \yii\db\ActiveRecord {

    public $template;
    
    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'sms_validator';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['name', 'mobile', 'code', 'created_at'], 'required'],
            [['created_at', 'times'], 'integer'],
            [['name'], 'string', 'max' => 20],
            [['mobile'], 'string', 'max' => 11],
            [['code'], 'string', 'max' => 4]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id'         => 'ID',
            'name'       => '类型',
            'mobile'     => '手机号',
            'code'       => '验证码',
            'times'      => '重复发送次数',
            'created_at' => '过期时间',
        ];
    }

    /** @inheritdoc */
    public function beforeSave($insert) {
        if ($insert) {
            static::deleteAll("created_at<:time", [':time' => time()-600]);
            $this->setAttribute('created_at', time());
            $this->setAttribute('code', mt_rand(1111, 9999));
            $this->setAttribute('times', 1);
        }
        else {
            $this->setAttribute('created_at', time());
            $this->times += 1;
        }

        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes) {


        return parent::afterSave($insert, $changedAttributes);
    }

    public function getContent($name, $code) {
        $template = $this->template[$name];
        return str_replace('{code}', $code, $template);        
    }

    public function send($mobile, $name) {
        
        if (strlen($mobile) != 11 || ! is_numeric($mobile)) {
            return [100022, '手机格式不正确'];
        }
        
        $sms  = self::findOne(['mobile' => $mobile, 'name' => $name]);
        if ($sms) {
            if ($sms->times > 4) {
                $sms->delete();
                $sms = new self();
            }
            if (($sms->created_at + 60) > time()) {
                return [100023, '请求过于频繁'];
            }
        }
        else {
            $sms = new self();
        }
        $data = array();
        $sms->attributes = ['mobile' => $mobile, 'name' => $name];         
        if ($sms->save(FALSE)) {
            $smser = Yii::$app->smser;
            $smser->send($sms->mobile, $this->getContent($name, $sms->code));
            $data = [($smser->state == 1 ? true : 100024), $smser->message];
        }
        else {
            $data = [100025, '短信发送出错'];
        }
        return $data;
    }

    public function validateCode($mobile, $name, $code) {
        $data = array();
        $sms  = self::findOne(['mobile' => $mobile, 'name' => $name, 'code' => $code]);
        if ($sms) {
            if ($sms->created_at+600 < time()) {
                $data = [100027, '该验证码已超时，请重新获取'];
            }
            else {
                $data = [true, 'ok'];                
            }
            $sms->delete();
        }
        else {
            $data = [100026, '短信验证码检验失败'];
        }
        return $data;
    }
}
